var config = require("../../config");
var async = require('async');
var path = require('path');
var fs = require('fs');
var admin = './database/admin.json';
var navigator = './database/navigator.json';
var articles = './database/articles.json';
var recycle = './database/recycle.json';

exports.requireAuthentication = function (req, res, next) {
  var user = req.session.user;
	if (!user) {
		return res.redirect("/admin/login");
	}
	next();
};

exports.postLogin = function (req, res) {
  var params = req.body, username = params.account,
    password = params.password;
  async.parallel([
    function (cb) {
      var _admin = JSON.parse(fs.readFileSync(admin));
      cb(null, _admin);
    }
  ], function (error, results) {
    var admin = results[0];
    if (username == admin.account) {
      var user = { username: username };
      req.session.regenerate(function(err) {
        if(err){
          return res.send({'status': 0, 'msg': 'fail'});
        }
        //登录成功就记录session
        req.session.user=user;
        req.session.success=1;
        res.send({'status': 1, 'msg': 'ok'});
      });
    } else {
      res.send({
        'status': 0,
        'msg': '密码或账户错误!'
      });
    }
  });
}

exports.logout = function (req, res) {
  req.session.destroy(function(err) {
    if(err){
      return res.send({'status': 0, 'msg': '退出登录失败!'});
    }
    res.clearCookie('keydone');
    res.redirect('/');
  });
};

exports.postLogout = function (req, res) {
  var action = req.body.action;
  if (action == 'logout') {
    req.session.destroy(function(err) {
      if(err){
        return res.send({'status': 0, 'msg': '退出登录失败!'});
      }
      res.clearCookie('keydone');
      res.redirect('/');
    });
  }
}

exports.admin = function (req, res) {
  async.parallel([
    function (cb) {
      var _articles = JSON.parse(fs.readFileSync(articles));
      cb(null, _articles);
    }
  ], function (error, results) {
    var articles = [], number=-1;
    for (var item in results[0]) {
      number++;
      if (number <= 21) {
        articles.push(results[0][item]);
      } else {
        break;
      }
    }
    res.render('admin/admin', {
      config: config,
      articles: articles
    });
  });
}

exports.articles = function (req, res) {
  var params = req.body, curpage=params.curpage || 1, pageNum = params.pageNum || 20;
  async.parallel([
    function (cb) {
      var _articles = JSON.parse(fs.readFileSync(articles)), arr = [], i = -1, count = -1;
      for (var item in _articles) {
        if (_articles[item]['title']) {
          i++;
          if (i >= (curpage-1) * pageNum && i < curpage * pageNum) {
            count++;
            arr.push(_articles[item]);
            if (count >= (pageNum-1)) break;
          }
        }
      }
      cb(null, arr);
    }
  ], function (error, results) {
    var _arr = results[0], article = {'list':_arr, 'curpage':curpage};
    res.send(article);
  });
}

exports.articleManage = function (req, res) {
  var params = req.body, id = params.id, type = params.type;
  var article = JSON.parse(fs.readFileSync(articles));
  if (type == 0) {
    article[id].availble = 0;
    article['availble']--;
  } else if(type == 1){
    article[id].availble = 1;
    article['availble']++;
  } else if (type == 2) {
    var recyclebin = JSON.parse(fs.readFileSync(recycle));
    article['total']--;
    if (article[id]['availble']){
      article['availble']--;
    }
    article[id].availble = 0;
    recyclebin[id] = article[id];
    fs.writeFileSync(recycle, JSON.stringify(recyclebin));
    delete article[id];
  }
  fs.writeFileSync(articles, JSON.stringify(article));
  if (type == 0) {
    res.send({
      status: 0,
      msg: '文章已隐藏!'
    });
  } else if(type == 1){
    res.send({
      status: 1,
      msg: '文章已显示!'
    });
  } else if (type == 2) {
    res.send({
      status: 2,
      msg: '文章已删除!'
    });
  }
}

exports.editArticle = function (req, res) {
  var params = req.query, id = params.id, source = params.source;
  // id: 文章 id, source: 文章来源, 可能在回收站里
  var article = JSON.parse(fs.readFileSync(source == 1 ? articles : recycle));
  res.render('admin/editArticle', {
    config: config,
    article: article[id],
    source: source
  });
}
